import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_demo/http/api.dart';
import 'package:flutter_demo/other/application.dart';
import 'package:flutter_demo/widget/buttons.dart';
import 'package:flutter_demo/widget/tiny_widgets.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:universal_html/html.dart';

class BaseInforModule extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _BaseInforModuleState();
}

class _BaseInforModuleState extends State<BaseInforModule> {

  late GlobalKey formKey;

  late TextEditingController birthAddressController;
  late TextEditingController phoneController;
  late TextEditingController archivesInstitutionController;
  late TextEditingController nationController;
  late TextEditingController politicCountenanceController;
  late TextEditingController languageMsgController;
  late TextEditingController specialtyMsgController;
  late TextEditingController RPMsgController;
  late TextEditingController scienceMsgController;

  bool isSubmitSuccess = false;
  late int birthMill;

  @override
  void initState() {
    super.initState();
    formKey = GlobalKey<FormState>();

    birthAddressController = TextEditingController();
    phoneController = TextEditingController();
    archivesInstitutionController = TextEditingController();
    nationController = TextEditingController();
    politicCountenanceController = TextEditingController();
    languageMsgController = TextEditingController();
    specialtyMsgController = TextEditingController();
    RPMsgController = TextEditingController();
    scienceMsgController = TextEditingController();
  }

  @override
  Widget build(BuildContext context) {
    return SliverToBoxAdapter(
      child: item(),
    );
  }

  Widget item() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        C(30),
        Form(
          key: formKey,
          child: Wrap(
            spacing: 30,
            runSpacing: 20,
            children: [
              ChooseDateView(title: '出生年月',
                  callback: (mill) => birthMill = mill),
              formField('出生地', 20, birthAddressController),
              formField('电话', 15, phoneController),
              formField('民族', 10, nationController),
              formField('政治面貌', 10, politicCountenanceController),
              formField('档案所在地机构名称', 15, archivesInstitutionController),
              bigFormField('技能/语言', 1000, languageMsgController),
              bigFormField('兴趣/特长', 1000, specialtyMsgController),
              bigFormField('奖惩情况', 1000, RPMsgController),
              bigFormField('学术经历', 1000, scienceMsgController),
            ],
          ),
        ),
        C(20),
        Container(
          alignment: Alignment.centerRight,
          padding: EdgeInsets.only(
            right: 40,
          ),
          child: BaseButton(
            radius: 4,
            width: 70,
            height: 36,
            withBorder: false,
            withShadow: false,
            centerButton: false,
            enabled: !isSubmitSuccess,
            buttonColor: Colors.blue,
            onTap: () {
              if ((formKey.currentState as FormState).validate())
                validatePassed(context, () {
                  setState(() => isSubmitSuccess = true);
                });
            },
            child: Text(
              '保存',
              style: TextStyle(
                color: Colors.white,
                fontSize: 14,
              ),
            ),
          ),
        ),
        C(30),
        Container(
          width: double.infinity,
          height: 1,
          margin: EdgeInsets.symmetric(horizontal: 32),
          decoration: BoxDecoration(
            color: Color(0xffeeeeee),
          ),
        ),
      ],
    );
  }

  Widget formField(String title, int maxSize,
      TextEditingController controller, {String? input}) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          width: 100,
          height: 40,
          alignment: Alignment.centerRight,
          margin: EdgeInsets.only(
            left: 15,
            right: 10,
          ),
          child: Text(
            title,
            textAlign: TextAlign.center,
            style: TextStyle(
              color: Color(0xff606266),
              fontSize: 14,
            ),
          ),
        ),
        Container(
          width: 220,
          padding: const EdgeInsets.only(
            left: 10,
            right: 15,
          ),
          child: TextFormField(
            controller: controller,
            decoration: InputDecoration(
              hintText: '请填写${input ?? title}',
              hintStyle: const TextStyle(
                fontSize: 14,
                color: Color(0xff606266),
              ),
              border: InputBorder.none,
            ),
            validator: (value) {
              if (value!.trim().isEmpty) {
                return '${input ?? title}不能为空';
              } else if (value.trim().length > maxSize) {
                return '${input ?? title}超出最大长度';
              } else {
                return null;
              }
            },
          ),
          decoration: BoxDecoration(
            border: Border.all(color: Colors.black26, width: 1),
            borderRadius: BorderRadius.circular(5),
          ),
        ),
      ],
    );
  }

  Widget bigFormField(String title, int maxSize,
      TextEditingController controller, {String? input}) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          width: 100,
          height: 40,
          alignment: Alignment.centerRight,
          margin: EdgeInsets.only(
            left: 15,
            right: 10,
          ),
          child: Text(
            title,
            textAlign: TextAlign.center,
            style: TextStyle(
              color: Color(0xff606266),
              fontSize: 14,
            ),
          ),
        ),
        Container(
          width: 614,
          height: 120,
          padding: const EdgeInsets.only(
            left: 10,
            right: 8,
          ),
          child: TextFormField(
            controller: controller,
            maxLines: 13,
            decoration: InputDecoration(
              hintText: '请填写${input ?? title}',
              hintStyle: const TextStyle(
                fontSize: 14,
                color: Color(0xff606266),
              ),
              border: InputBorder.none,
            ),
            validator: (value) {
              if (value!.trim().isEmpty) {
                return '${input ?? title}不能为空';
              } else if (value.trim().length > maxSize) {
                return '${input ?? title}超出最大长度';
              } else {
                return null;
              }
            },
          ),
          decoration: BoxDecoration(
            border: Border.all(color: Colors.black26, width: 1),
            borderRadius: BorderRadius.circular(5),
          ),
        ),
      ],
    );
  }

  Future<void> validatePassed(BuildContext context,
      void Function() callback) async {
    Response response = await SystemApi.base_infor(
        Application.currentAccount,
        birthMill,
        birthAddressController.text,
        phoneController.text,
        archivesInstitutionController.text,
        nationController.text,
        politicCountenanceController.text,
        languageMsgController.text,
        specialtyMsgController.text,
        RPMsgController.text,
        scienceMsgController.text,
    );
    var map = json.decode(response.data);
    if (response.statusCode == 200 && map['code'] == '1') {
      Fluttertoast.showToast(msg: map['msg']);
      callback.call();
    } else if (map['code'] != '1') {
      Fluttertoast.showToast(msg: map['msg']);
    } else {
      Fluttertoast.showToast(msg: response.statusCode.toString());
    }
  }
}